<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/10
 * Time: 18:51
 */

namespace app\common\model;

use app\common\cachemodel\Article as ArticleCacheModel;
use app\common\lib\exception\ApiException;
use think\Cache;

/**
 * 星文相关接口
 * Class Article
 * @package app\common\model
 */
class Article extends Base
{
    protected $table = 'wechatadmin.system_article';

    const FORTUNE = 'fortune_'; //运势文章缓存键名
    const INDEX_ARTICLES = 'index_articles';//首页文章缓存键名
    const ARTICLE_CATEGORY = 'article_caregory_';//分类文章缓存键名
    const ARTICLE = 'article_'; //文章详情缓存键名
    const ARTICLE_CONTENT = 'article_content_'; //文章内容缓存键名
    const ARTICLE_READ = 'article_read_'; //已读文章缓存键名
    const ARTICLE_GOOD = 'article_good_'; //用户点赞文章缓存键名
    const ARTICLE_GOOD_TIME = 'article_good_time_'; //用户点赞文章时间缓存
    const ARTICLE_COLLECT = 'article_collect_';//用户收藏文章缓存键名
    const ARTICLE_COLLECT_TIME = 'article_collect_time_';//用户收藏文章时间缓存
    const READ_DELAY = 'read_delay_'; //文章已读延迟缓存键名
//    const CACHE_TIME = 86400 * 7;
    const CACHE_TIME = 86400;
    const CACHE_TIME_INDEX = 86400;//首页文章的缓存时间
    const CACHE_TIME_SHORT = 300;//收藏或点赞等时间的缓存时间
    const CACHE_TIME_CATEGORY = 900;// 文章列表ids缓存时间

    /**
     * 关联评论模型
     * @return \think\model\relation\HasMany
     */
    public function comments()
    {
        return $this->hasMany('ArticleComment', 'aid', 'id');
    }

    /**
     * 关联文章点赞模型
     * @return \think\model\relation\HasMany
     */
    public function good()
    {
        return $this->hasMany('ArticleGood', 'aid', 'id');
    }

    /**
     * 关联文章收藏模型
     * @return \think\model\relation\HasMany
     */
    public function collect()
    {
        return $this->hasMany('ArticleCollect', 'aid', 'id');
    }

    /**
     * 关联文章阅读模型
     * @return \think\model\relation\HasMany
     */
    public function reads()
    {
        return $this->hasMany('ArticleRead', 'aid', 'id');
    }

    /**
     * 关联文章作者模型
     * @return \think\model\relation\BelongsTo
     */
    public function author()
    {
        return $this->belongsTo('ArticleAuthor', 'id', 'aid')->field('name author,thumb avatar');
    }

    /**
     * 获取【周运、月运、年运】运势文章
     * @param string $type
     * @param int $in_sign
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     * @throws ApiException
     */
    public function getFortune($type = 'week', $in_sign = 1)
    {
        $time_now = time();

        if (strtolower($type) == 'month')
        {
            $type_day = date('Y_m', $time_now);
        } elseif (strtolower($type) == 'year')
        {
            $type_day = date('Y', $time_now);
        } elseif (strtolower($type) == 'day'){
            $type_day = date('Y_m_d', $time_now);
        }else
        {
            $type_day = date('Y_m_d', strtotime('this week Monday', $time_now));
        }

        $yunshi_arr = [
            'day' => ['id' => 1, 'sub' => [0, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65]],
            'week' => ['id' => 4, 'sub' => [0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]],
            'month' => ['id' => 17, 'sub' => [0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]],
            'year' => ['id' => 18, 'sub' => [0, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42]],
        ];

        $map['cid'] = $yunshi_arr[$type]['sub'][$in_sign];

        if (!$map['cid'])
        {
            // 错误信息写入日志
//            \think\Log::write('in_sign:' . $in_sign, 'error');
//            \think\Log::write(var_export(request()->param(),true), 'error');
//            \think\Log::write(var_export(request()->header(),true), 'error');
            throw new ApiException('运势获取失败');
        }

        $map['status'] = 1;

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::FORTUNE . $type . '_' . $map['cid'] . '_' . $type_day);
        }

        if ($data === false)
        {
            try
            {
                $field = 'id,cid,title,introduction,content,publish_time,whole,health,career,love,money';
                $data = $this->field($field)->where($map)
                    ->whereTime('publish_time', '<', $time_now)
                    ->order('publish_time DESC')
                    ->findOrFail()->toArray();

            }
            catch (\Exception $e)
            {
                // 错误信息写入日志
                \think\Log::write('getFortune: ' . $e->getMessage(), 'error');

                throw new ApiException('运势获取失败');
            }

            if (!empty($data))
            {
                if (strtolower($type) == 'month' && date('Y_m', strtotime($data['publish_time'])) == $type_day)
                {
                    Cache::set(self::FORTUNE . $type . '_' . $map['cid'] . '_' . $type_day, $data, self::CACHE_TIME);
                } elseif (strtolower($type) == 'year' && date('Y', strtotime($data['publish_time'])) == $type_day)
                {
                    Cache::set(self::FORTUNE . $type . '_' . $map['cid'] . '_' . $type_day, $data, self::CACHE_TIME);
                } else
                {
                    if (date('Y_m_d', strtotime($data['publish_time'])) == $type_day)
                        Cache::set(self::FORTUNE . $type . '_' . $map['cid'] . '_' . $type_day, $data, self::CACHE_TIME);
                }
            }
        }
        return $data;
    }

    /**
     * 获取首页显示的文章列表 最多10条记录
     * @param array $map
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     * @throws \Exception
     */
    public function getIndexArticle($map = [])
    {
        $pageData = (new ArticleCacheModel())->getArticleIndexIds($map['uid'], 1, 1, 20);
        return $pageData['data'] ?? [];
        $time_now = time();

        $uid = $map['uid'];
        unset($map['uid']);
        $ucid = $map['uc_id'];
        unset($map['uc_id']);

        $data = false;

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::INDEX_ARTICLES);
        }

        if ($data === false)
        {
            try
            {
                $data = $this->alias('a')
                    ->field('a.id,a.cid,a.is_hot,a.title,a.introduction,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`')
                    ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'INNER')
                    ->where($map)
                    ->whereTime('a.publish_time', '<', $time_now)// 查看当前时间以前的文章  预发布文章不显示
                    ->order('a.sort DESC,a.publish_time DESC')
                    ->limit(20)
                    ->selectOrFail();

                $data = json_decode(json_encode($data, true), true);

                Cache::set(self::INDEX_ARTICLES, $data, self::CACHE_TIME_SHORT);
            }
            catch (\Exception $e)
            {
                $data = [];
            }
        }

        if (!empty($data))
        {
            $article_read = $this->getUserArticleRead(['uid' => $uid]);
            $article_good = $this->getUserArticleGood(['uid' => $uid, 'ucid' => $ucid]);
            foreach ($data as $k => $d)
            {

                $data[$k]['publish_time'] = strtotime($d['publish_time']);

                $data[$k]['good'] += floor($data[$k]['read'] / 30);

                if (strpos($article_read, (string)$d['id']) >= 1) $data[$k]['is_read'] = true;
                if (strpos($article_good, (string)$d['id']) >= 1) $data[$k]['good_status'] = true;
            }
        }

        return $data;
    }

    /**
     * 获取栏目下的所有文章（获取文章列表不需要获取文章的内容，因为文章的内容比较大，redis的读取、写入带宽有限制）
     * @param array $map
     * @return array
     * @throws \Exception
     */
    public function getArticleList($map = [], $resType = 1)
    {
        return (new ArticleCacheModel())->getPageArticleList($map['uid'], $map['cid'], $resType, $map['page']);
        die;
        $page = $map['page'];
        $cid = $map['cid'];
        $uid = $map['uid'];
        $ucid = $map['uc_id'];

        $time_now = time();

        $article_category_str = false;
        if ($this->cache_on >= 1)
        {
            $article_category_str = Cache::get(self::ARTICLE_CATEGORY . $cid);// 获取当前栏目文章id数组
        }

        if ($article_category_str === false)
        {
            try
            {
                $article_category_list = $this->table('wechatadmin.system_article')->alias('a')
                    ->field('a.id')
                    ->join('wechatadmin.system_article_category ac', 'a.id=ac.aid')
                    ->where('a.status=1 and ac.cid=' . $cid)
                    ->whereTime('a.publish_time', '<', $time_now)
                    ->order('a.sort DESC,a.publish_time DESC')
                    ->selectOrFail();

                $article_category_list = json_decode(json_encode($article_category_list, true), true);

                if (!empty($article_category_list)) foreach ($article_category_list as $acl) $article_category_str .= $acl['id'] . ',';

                $article_category_str = substr($article_category_str, 0, -1);

                Cache::set(self::ARTICLE_CATEGORY . $cid, $article_category_str, self::CACHE_TIME_CATEGORY);
            }
            catch (\Exception $e)
            {
                $article_category_str = '';// 文章列表默认为空

                \think\Log::write('getArticleList：' . $e->getMessage(), 'error');
            }
        }

        $article_category_list = explode(',', $article_category_str);

        $total = count($article_category_list);

        $per_page = 10;// 当前栏目文章总数
        $current_page = $page;// 当前栏目文章总数
        $last_page = ceil($total / $per_page);// 最后一页的页码

        $start = ($current_page - 1) * $per_page;// 开始id

        $article_category = array_slice($article_category_list, $start, $per_page);// 取出当前页所需的文章id数组

        $result = [
            'total' => $total,
            'per_page' => $per_page,
            'current_page' => $current_page,
            'last_page' => $last_page,
            'data' => [],
        ];


        if (!empty($article_category))
        {
            $aids = [];
            $temp = [];

            if ($uid)
            {
                $article_read = $this->getUserArticleRead(['uid' => $uid]);
                $article_good = $this->getUserArticleGood(['uid' => $uid, 'ucid' => $ucid]);
            } else
            {
                $article_read = '';
                $article_good = '';
            }

            foreach ($article_category as $aid)
            {
                if ($this->cache_on >= 1)
                {
                    $temp[$aid] = Cache::get(self::ARTICLE . $aid);// 获取文章内容
                }
                if (!isset($temp[$aid]) || empty($temp[$aid]))
                {
                    $aids[] = $aid;
                    $temp[$aid] = false;
                }
            }
            if (!empty($aids) || count($aids) > 0)
            {
                try
                {
                    $field = 'a.id,a.cid,a.title,a.introduction,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,is_hot';
                    $articles = $this->table('wechatadmin.system_article')->alias('a')
                        ->field($field)
                        ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'LEFT')
                        ->where(['a.id' => ['in', $aids]])
                        ->selectOrFail();
                    $articles = json_decode(json_encode($articles, true), true);
                }
                catch (\Exception $e)
                {
                    $articles = [];
                }

                if (!empty($articles))
                {
                    foreach ($articles as $a)
                    {
                        Cache::set(self::ARTICLE . $a['id'], $a, self::CACHE_TIME);
                        $temp[$a['id']] = $a;
                    }
                }
            }

            foreach ($article_category as $aid)
            {
                if ($temp[$aid] === false)
                {
                    continue;
                }
                $temp[$aid]['is_read'] = false;
                $temp[$aid]['good_status'] = false;
                $temp[$aid]['publish_time'] = strtotime($temp[$aid]['publish_time']);
                $temp[$aid]['good'] += floor($temp[$aid]['read'] / 30);

                if (strpos($article_read, (string)$aid) >= 1) $temp[$aid]['is_read'] = true;
                if (strpos($article_good, (string)$aid) >= 1) $temp[$aid]['good_status'] = true;

                $result['data'][] = $temp[$aid];
            }
        }
        return $result;
    }

    /**
     * 获取用户所有已读的文章id 字符串
     * @param array $map
     * @return mixed|string
     */
    public function getUserArticleRead($map = [])
    {
        $article_read = false;

        $uid = $map['uid'];

        if ($this->cache_on >= 1)
        {
            $article_read = Cache::get(self::ARTICLE_READ . $uid);
        }
        if ($article_read === false)
        {
            try
            {
                $user_reads = $this->table('wechat_backup_07_18_14_43_00.app_user_article')->field('aid')->where('uid', $uid)->select();

                $user_reads = json_decode(json_encode($user_reads, true), true);

                if (!empty($user_reads)) foreach ($user_reads as $ua) $article_read .= ',' . $ua['aid'];

                Cache::set(self::ARTICLE_READ . $uid, $article_read, self::CACHE_TIME_SHORT);
            }
            catch (\Exception $e)
            {
                $article_read = '';
            }
        }

        return $article_read;
    }

    /**
     * 获取用户所有点赞的文章id 字符串 或者 获取用户所有点赞的文章id和time 数组
     * @param array $map
     * @param int $is_return_time
     * @return array|bool|mixed|string
     */
    public function getUserArticleGood($map = [], $is_return_time = 0)
    {
        $data = false;
        $article_good_time = false;

        $uid = $map['uid'];
        $ucid = $map['ucid'];

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::ARTICLE_GOOD . $uid);
            $article_good_time = Cache::get(self::ARTICLE_GOOD_TIME . $uid);
        }
        if ($data === false || $article_good_time === false)
        {
            try
            {
                $list = $this->table('wechatadmin.system_article_good')->field('aid,create_time')->where('ucid', $ucid)->select();

                $list = json_decode(json_encode($list, true), true);

                if (!empty($list)) foreach ($list as $ag)
                {
                    $data .= ',' . $ag['aid'];
                    $article_good_time .= ',' . $ag['create_time'];
                };

                Cache::set(self::ARTICLE_GOOD . $uid, $data, self::CACHE_TIME_SHORT);
                Cache::set(self::ARTICLE_GOOD_TIME . $uid, $article_good_time, self::CACHE_TIME_SHORT);

            }
            catch (\Exception $e)
            {
                $data = '';
                $article_good_time = [];
            }
        }

        if ($is_return_time == 0)
        {
            return $data;
        } else
        {
            return ['ids' => $data, 'times' => $article_good_time];
        }
    }

    /**
     * 获取用户所有收藏文章的id 或者 获取用户所有收藏的文章id和time 数组
     * @param array $map
     * @param int $is_return_time
     * @return mixed|string
     */
    public function getUserArticleCollect($map = [], $is_return_time = 0)
    {
        $data = false;
        $article_collect_time = false;

        $uid = $map['uid'];
        $ucid = $map['ucid'];

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::ARTICLE_COLLECT . $uid);
            $article_collect_time = Cache::get(self::ARTICLE_COLLECT_TIME . $uid);
        }
        if ($data === false || $article_collect_time === false)
        {
            try
            {
                $list = $this->table('wechatadmin.system_article_collect')->field('aid,create_time')->where('ucid', $ucid)->select();

                $list = json_decode(json_encode($list, true), true);

                if (!empty($list)) foreach ($list as $ag)
                {
                    $data .= ',' . $ag['aid'];
                    $article_collect_time .= ',' . $ag['create_time'];
                }

                Cache::set(self::ARTICLE_COLLECT . $uid, $data, self::CACHE_TIME_SHORT);
                Cache::set(self::ARTICLE_COLLECT_TIME . $uid, $article_collect_time, self::CACHE_TIME_SHORT);
            }
            catch (\Exception $e)
            {
                $data = '';
                $article_collect_time = [];
            }
        }

        if ($is_return_time == 0)
        {
            return $data;
        } else
        {
            return ['ids' => $data, 'times' => $article_collect_time];
        }
    }

    /**
     * 获取文章详情
     * @param $uid
     * @param array $map
     * @param int $time_type 0=>时间戳,1=>字符串
     * @return array|bool|false|mixed|\PDOStatement|string|\think\Model
     * @throws ApiException
     * @throws \think\Exception
     * @throws \Exception
     */
    public function getArticleDetails($uid, $map = [], $time_type = 1)
    {
        $articleModel = new ArticleCacheModel();
        $data = current($articleModel->batchGetInfo([$map['id']], ['id', 'title', 'introduction', 'content', 'author', 'avatar', 'thumb', 'publish_time', 'good', 'collect', 'read', 'read_base', 'is_hot', 'a_id']));
        if ($data)
        {
            $data = $articleModel->articleDetailDataReset($uid, (int)$map['id'], $data, $time_type);
        }

//        $id = $map['id'];
//
//        if (!$map['id'])
//        {
//            // 错误信息写入日志
//            \think\Log::write('getArticleDetails: article ID:' . $id, 'error');
//
//            throw new ApiException('文章获取失败');
//        }
//
//        $data = false;
//        $content = false;//文章内容
//        if ($this->cache_on >= 1)
//        {
//            $data = Cache::get(self::ARTICLE . $id);
//            // 获取文章内容
//            if ($is_get_content == 1)
//            {
//                $content = Cache::get(self::ARTICLE_CONTENT . $id);
//            }
//        }
//
//        if ($data === false || ($content === false && $is_get_content == 1))
//        {
//            try
//            {
//                $field = 'a.id,a.cid,a.title,a.introduction,a.status,a.content,u.name author,a.comment,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,t.name type_name,t.name_en type_name_en,is_hot';
//                $data = $this->table('wechatadmin.system_article')->alias('a')
//                    ->field($field)
//                    ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'LEFT')
//                    ->join('wechatadmin.system_article_type t', 't.id=a.tid', 'LEFT')
//                    ->where('a.id', $id)
//                    ->where('a.status', 1)
//                    ->find();
//
//                if ($data)
//                {
//                    $content = $data->data['content'];//设置文章内容
//                    unset($data->data['content']);//移除文章内容
//                } else
//                {//当status 为0时（文章被删除），需要设置缓存，否则会不断的请求sql
//                    $data = '';
//                    Cache::set(self::ARTICLE . $id, $data, self::CACHE_TIME);
//                }
//
//                $data = json_decode(json_encode($data, true), true);
//            }
//            catch (\Exception $e)
//            {
//                \think\Log::write('[' . $id . '] getArticleDetails：' . $e->getMessage(), 'error');
////                throw new ApiException('文章获取失败');
//            }
//        }
//
//        if (!empty($data) && !empty($content))
//        {
//            $data['read']++;
//
//            if (!isset($data['read_delay'])) $data['read_delay'] = $data['read'];
//
//            Cache::set(self::ARTICLE . $id, $data, self::CACHE_TIME);
//            Cache::set(self::ARTICLE_CONTENT . $id, $content, self::CACHE_TIME);//把文章内容写入缓存
//
//            if ($is_get_content == 1)
//            {
//                $data['content'] = $content;
//            }
//
//            $data['good'] += floor($data['read'] / 30);
//
//            if (isset($map['uid']) && isset($map['ucid']))
//            {
//                $uid = $map['uid'];
//                $ucid = $map['ucid'];
//
//                $data['good_status'] = false;
//                $data['collect_status'] = false;
//                if ($map['is_old'] !== false) $data['publish_time'] = strtotime($data['publish_time']);
//
//                $article_read = $this->getUserArticleRead(['uid' => $uid]);
//                $article_good = $this->getUserArticleGood(['uid' => $uid, 'ucid' => $ucid]);
//                $article_collect = $this->getUserArticleCollect(['uid' => $uid, 'ucid' => $ucid]);
//
//                if (!strpos($article_read, (string)$id))
//                {
//                    $insert = ['aid' => $id, 'uid' => $uid];
//
//                    $new_id = $this->table('wechat_backup_07_18_14_43_00.app_user_article')->insertGetId($insert);
//
//                    $article_read .= ',' . $new_id;
//                    // 更新用户已读缓存
//                    Cache::set(self::ARTICLE_READ . $uid, $article_read, self::CACHE_TIME_SHORT);
//                }
//
//                if (strpos($article_good, (string)$id)) $data['good_status'] = true;
//                if (strpos($article_collect, (string)$id)) $data['collect_status'] = true;
//            } else
//            {
//                $data['good_status'] = false;
//                $data['collect_status'] = false;
//                if ($map['is_old'] !== false) $data['publish_time'] = strtotime($data['publish_time']);
//            }
//        }
//        if ($this->cache_on >= 1)
//        {
//            $read_cache = Cache::get(self::READ_DELAY . $map['id']);
//
//            if ($read_cache === false) $read_cache = 0;
//
//            $read_cache++;
//
//            $read_delay_add = config('article.read_delay_add') * 1;
//
//            if ($read_cache >= $read_delay_add)
//            {
//
//                $this->table('wechatadmin.system_article')->where('id', $map['id'])->setInc('read', $read_delay_add);
//
//                $read_cache = 0;
//            }
//
//            Cache::set(self::READ_DELAY . $map['id'], $read_cache);
//        }

        return $data;
    }

    /**
     * @param array $map
     * @return string
     * @throws \think\Exception
     * @throws \Exception
     */
    public function ArticleGood($map = [])
    {
        $articleGood = new ArticleGood();
        //获取用户已点赞的aid
        $goods = (new ArticleGood())->getGoodFromCache($map['uid'], 1);
        if (in_array($map['id'], $goods))
        {
            //取消点赞
            $articleGood->delData($map['uid'], $map['id'], ['aid' => $map['id'], 'uid' => $map['uid'], 'type' => 1], 1);
        } else
        {
            //添加点赞
            $articleGood->saveData($map['uid'], $map['id'], ['aid' => $map['id'], 'uid' => $map['uid'], 'create_time' => time(), 'type' => 1], 1);
        }
        return;

        $id = $map['id'];
        $uid = $map['uid'];
        $ucid = $map['ucid'];
        $time = time();

        $data = $article = false;
        $article_good_time = false;//文章点赞时间

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::ARTICLE_GOOD . $uid, '');
            $article = Cache::get(self::ARTICLE . $id);
            $article_good_time = Cache::get(self::ARTICLE_GOOD_TIME . $uid, '');
        }
        if ($data === false || $article_good_time === false)
        {

            try
            {
                $temp = $this->table('wechatadmin.system_article_good')->field('aid,create_time')->where(['ucid' => $ucid, 'aid' => $id])->selectOrFail();

                $temp = json_decode(json_encode($temp, true), true);

                foreach ($temp as $t)
                {
                    $data .= ',' . $t['aid'];
                    $article_good_time .= ',' . $t['create_time'];
                }

            }
            catch (\Exception $e)
            {
                $data = '';
            }
        }
        if ($article === false)
        {
            $field = 'a.id,a.cid,a.title,a.introduction,a.content,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,t.name type_name,t.name_en type_name_en,is_hot';
            try
            {
                $article = $this->table('wechatadmin.system_article')->alias('a')
                    ->field($field)
                    ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'INNER')
                    ->join('wechatadmin.system_article_type t', 't.id=a.tid', 'LEFT')
                    ->where('a.id', $id)
                    ->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $article = [];
            }

        }

        // 已赞，进行取消
        if (!empty($id) && $start = strpos($data, (string)$id))
        {
            $this->table('wechatadmin.system_article_good')->where(['ucid' => $ucid, 'aid' => $id])->delete();

            $this->table('wechatadmin.system_article')->where('id', $id)->setDec('good');

            if (!empty($article))
            {
                $article['good']--;
                Cache::set(self::ARTICLE . $id, $article, self::CACHE_TIME);// 更新文章缓存
            }

            // 更新用户点赞时间的缓存 start
            try
            {
                $actime = $this->getValueInOtherData($id, $data, $article_good_time);
                if ($actime > 0)
                {//说明找到了index，那么从用户收藏数组中找出来
                    $article_good_time = str_replace(',' . (string)$actime, '', $article_good_time);
                    Cache::set(self::ARTICLE_GOOD_TIME . $uid, $article_good_time, self::CACHE_TIME_SHORT);
                }
            }
            catch (\Exception $e)
            {
                \think\Log::write('ArticleGood: 更新[' . $uid . ']用户点赞文章[' . $id . ']的时间缓存失败', 'error');
                Cache::rm(self::ARTICLE_GOOD_TIME . $uid);
            }
            // 更新用户点赞时间的缓存 end

            // 更新用户点赞缓存
            $data = str_replace(',' . (string)$id, '', $data);
            Cache::set(self::ARTICLE_GOOD . $uid, $data, self::CACHE_TIME_SHORT);

            return 'Cancel good success.';
        } else
        {
            $this->table('wechatadmin.system_article_good')->insert(['ucid' => $ucid, 'aid' => $id, 'uid' => $uid, 'create_time' => $time]);

            $this->table('wechatadmin.system_article')->where('id', $id)->setInc('good');

            if (!empty($article))
            {
                $article['good']++;
                Cache::set(self::ARTICLE . $id, $article, self::CACHE_TIME);// 更新文章缓存
            }

            // 更新用户点赞缓存
            $data .= ',' . $id;
            Cache::set(self::ARTICLE_GOOD . $uid, $data, self::CACHE_TIME_SHORT);

            // 更新用户点赞时间的缓存
            $article_good_time .= ',' . $time;
            Cache::set(self::ARTICLE_GOOD_TIME . $uid, $article_good_time, self::CACHE_TIME_SHORT);

            return 'Good success.';
        }
    }

    /**
     * 文章收藏接口
     * @param array $map
     * @return string
     * @throws \think\Exception
     */
    public function ArticleCollect($map = [])
    {
        $id = $map['id'];
        $uid = $map['uid'];
        $ucid = $map['ucid'];
        $time = time();

        $data = false;
        $article_collect_time = false;//文章收藏时间

        if ($this->cache_on >= 1)
        {
            $data = Cache::get(self::ARTICLE_COLLECT . $uid, '');
            $article_collect_time = Cache::get(self::ARTICLE_COLLECT_TIME . $uid, '');
            $article = Cache::get(self::ARTICLE . $id);
        }
        if ($data === false || $article_collect_time === false)
        {
            $data = '';
            $article_collect_time = [];
            try
            {
                $temp = $this->table('wechatadmin.system_article_collect')->field('aid,create_time')->where(['ucid' => $ucid, 'aid' => $id])->selectOrFail();

                $temp = json_decode(json_encode($temp, true), true);

                foreach ($temp as $t)
                {
                    $data .= ',' . $t['aid'];
                    $article_collect_time .= ',' . $t['create_time'];
                }

            }
            catch (\Exception $e)
            {

            }
        }
        if (empty($article))
        {
            $field = 'a.id,a.cid,a.title,a.introduction,a.content,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,t.name type_name,t.name_en type_name_en,is_hot';
            try
            {
                $article = $this->table('wechatadmin.system_article')->alias('a')
                    ->field($field)
                    ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'INNER')
                    ->join('wechatadmin.system_article_type t', 't.id=a.tid', 'LEFT')
                    ->where('a.id', $id)
                    ->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $article = [];
            }
        }

        // 已收藏，进行取消
        if ($start = strpos($data, (string)$id))
        {
            $this->table('wechatadmin.system_article_collect')->where(['ucid' => $ucid, 'aid' => $id])->delete();

            $this->table('wechatadmin.system_article')->where('id', $id)->setDec('collect');

            if (!empty($article))
            {
                $article['collect']--;
                Cache::set(self::ARTICLE . $id, $article, self::CACHE_TIME);// 更新文章缓存
            }

            // 更新用户收藏时间的缓存 start
            try
            {
                $actime = $this->getValueInOtherData($id, $data, $article_collect_time);
                if ($actime > 0)
                {//说明找到了index，那么从用户收藏数组中找出来
                    $article_collect_time = str_replace(',' . (string)$actime, '', $article_collect_time);
                    Cache::set(self::ARTICLE_COLLECT_TIME . $uid, $article_collect_time, self::CACHE_TIME_SHORT);
                }
            }
            catch (\Exception $e)
            {
                \think\Log::write('ArticleCollect: 更新[' . $uid . ']用户收藏文章[' . $id . ']的时间缓存失败', 'error');
                Cache::rm(self::ARTICLE_COLLECT_TIME . $uid);
            }
            // 更新用户收藏时间的缓存 end

            // 更新用户收藏缓存
            $data = str_replace(',' . (string)$id, '', $data);
            Cache::set(self::ARTICLE_COLLECT . $uid, $data, self::CACHE_TIME_SHORT);

            return 'Cancel collect success.';
        } else
        {
            $this->table('wechatadmin.system_article_collect')->insert(['ucid' => $ucid, 'aid' => $id, 'uid' => $uid, 'create_time' => $time]);

            $this->table('wechatadmin.system_article')->where('id', $id)->setInc('collect');

            if (!empty($article))
            {
                $article['collect']++;
                Cache::set(self::ARTICLE . $id, $article, self::CACHE_TIME);// 更新文章缓存
            }

            // 更新用户收藏缓存
            $data .= ',' . $id;
            Cache::set(self::ARTICLE_COLLECT . $uid, $data, self::CACHE_TIME);

            // 更新用户收藏时间的缓存
            $article_collect_time .= ',' . $time;
            Cache::set(self::ARTICLE_COLLECT_TIME . $uid, $article_collect_time, self::CACHE_TIME_SHORT);

            return 'Collect success.';
        }
    }

    /***
     * 获取 以“，”分隔的某个字符串中的某个元素的位置，然后从另外一个以“，”分隔的字符串中查询其中的值
     * @param $id
     * @param $data
     * @param $article_collect_time
     * @return int
     */
    private function getValueInOtherData($id, $data, $article_collect_time)
    {
        $actime = -1;

        // 获取该篇文章id，在缓存中的位置
        $aid_index = -1;
        $array_aids = explode(',', $data);//将$data转换为数组
        $array_article_collect_time = explode(',', $article_collect_time);//将$data转换为数组
        foreach ($array_aids as $index => $aid)
        {
            if ($aid == $id)
            {
                $aid_index = $index;
            }
        }
        if ($aid_index > 0)
        {//说明找到了index，那么从用户收藏数组中找出来
            $actime = $array_article_collect_time[$aid_index];
        }
        return $actime;
    }

    /**
     * 获取redis分页数据demo
     * HASH + Zset
     * @param array $map
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRedisPageList($map = [])
    {
        /**
         * 删除当前库redis
         */
//        self::$redis->clear('db');

        $field = 'a.id,a.cid,a.title,a.introduction,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,t.name type_name,t.name_en type_name_en,is_hot';

        $articles = $this->table('wechatadmin.system_article')->alias('a')
            ->field($field)
            ->join('wechatadmin.zhunle_article_author u', 'a.aid=u.id', 'INNER')
            ->join('wechatadmin.system_article_type t', 't.id=a.tid', 'LEFT')
            ->where(['a.cid' => $map['cid'], 'a.status' => 1])
            ->select();

        $articles = json_decode(json_encode($articles, true), true);

        foreach ($articles as $k => $d)
        {
            self::$redis->set_redis_page_info($d['id'], $d, 'article'); //插入数据
        }
        /**
         * 删除分页中某数据
         */
//        self::$redis->del_redis_page_info([61]); //删除数据

        $data = self::$redis->get_redis_page_info($map['page'], 10, ['id', 'cid', 'title', 'introduction'], 'article'); //获取分页数据

        return $data;
    }
}
